<?php
/**
 * 简历解析 Logic
 */

namespace app\common\queue;


use think\Cache;
use think\Exception;

/**
 * Class CommonQueue
 * @package app\common\queue
 */
class CommonQueue extends \Redis{
    protected static $inition;
    private $select = 15;
    private $config;
    /**
     * @var \Redis
     */
    private $redis;
    public $key;

    public function __construct($config=[])
    {
        !empty($config['queue_key']) && $this->key = $config['queue_key'];
        $this->config = config('commonqueue')[$this->key]??[];
//        $config['select'] = $this->select;
        $this->config += $config;

        $this->connect($this->config['host']);
        $this->select($this->config['select']);

        if($this->config['password'])
            $this->auth($this->config['password']);
        $this->key =  $this->config['prefix'].'_' . $this->key;

    }

    public function run(){
//        $this->setOption(self::OPT_READ_TIMEOUT, -1);
//        $time = date('Y-m-d H:i:s');
        echo date('Y-m-d H:i:s').PHP_EOL;
        try{
            while(true){
                $res = $this->blPop($this->key,50);
                cache('');// 在队列  或常驻系统中 要保持redis连接更新
                if(!$res || empty($res[1])){
                    continue;
                }
                echo date('Y-m-d H:i:s').'==='.PHP_EOL;
                $data = json_decode($res[1],1);
                $this->handle($data);
                echo 'handleSuccess=================='.PHP_EOL;
            }
        }catch (\RedisException $e){
            echo date('Y-m-d H:i:s').PHP_EOL;
            echo $e->getMessage().PHP_EOL;
            echo ($e->getTraceAsString()).PHP_EOL;
        }

    }
    public function action($params){

        $this->rPush($this->key,json_encode($params,256));
        return 1;
    }
    public function handle($data,$count = 0){
        try {
            $count || dolog($this->key.':Begin',$data);
            $res = call_user_func([$data['controller'],$data['action']],$data);
            dolog($this->key.':JobsHandle',[$res,$data]);
        }catch (\Exception $e){
            if($count <= 0){
                dolog($this->key.':Again',$data);
                return $this->handle($data,1);
            }
            dolog($this->key.'JobsError',[$e->getMessage(),$e->getFile(),$e->getLine()]);
//            dolog($this->key.'JobsError1',$e->getTraceAsString());
            file_put_contents(ROOT_PATH.'public/Extra.log',__METHOD__.'Error:'.date('Y-m-d H:i:s').$e->getTraceAsString().PHP_EOL,FILE_APPEND);
        }
    }
}